#include "MyWidget.h"

MyWidget::MyWidget(QWidget *parent) : QWidget(parent)
{
    resize(800, 600);
    m_menuButtonLayout = new QVBoxLayout;
    m_menuButtonLayout->setAlignment(Qt::AlignTop);
    m_menuTitle = new QLabel(this);
    m_menuTitle->setText("Menu");
    m_menuTitle->setAlignment(Qt::AlignCenter);

    m_searchButton = new QPushButton("Search", this);
    m_searchButton->setFixedSize(140, 30);
    m_menuButtonLayout->addWidget(m_menuTitle);
    m_menuButtonLayout->addWidget(m_searchButton);
    m_menuWidget = new QWidget(this);
    m_menuWidget->setLayout(m_menuButtonLayout);

    QFrame* line = new QFrame(this);
    line->setFrameShape(QFrame::VLine);
    line->setFrameShadow(QFrame::Sunken);

    m_stackWidget = new QStackedWidget(this);

    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->addWidget(m_menuWidget, 1);
    mainLayout->addWidget(line);
    mainLayout->addWidget(m_stackWidget, 4);

    setLayout(mainLayout);
    connect(m_searchButton, &QPushButton::clicked, this, &MyWidget::ShowUrlLineEdit);
}

void MyWidget::ShowUrlLineEdit()
{
    if (!m_urlLineEdit) {
        m_urlLineEdit = new QLineEdit(this);
        m_urlLineEdit->setPlaceholderText("Enter URL");
        m_urlLineEdit->setFixedHeight(40);
        m_urlLineEdit->setAlignment(Qt::AlignHCenter);
        connect(m_urlLineEdit, &QLineEdit::returnPressed, this, &MyWidget::ShowUrlPage);
    }
    m_stackWidget->addWidget(m_urlLineEdit);
    m_stackWidget->setCurrentWidget(m_urlLineEdit);
    m_urlLineEdit->show();
    m_urlLineEdit->setFocus();
    return;
}

void MyWidget::ShowUrlPage()
{
    QString url = m_urlLineEdit->text();
    if (!url.isEmpty()) {
        QWebView *webview = new QWebView(this);
        webview->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
        connect(webview, &QWebView::linkClicked, this, &MyWidget::OpenLink);
        webview->load(QUrl(url));
        m_stackWidget->addWidget(webview);
        m_stackWidget->setCurrentWidget(webview);
    }
    return;
}

void MyWidget::OpenLink(const QUrl& url)
{
    QWebView *webview = qobject_cast<QWebView*>(sender());
    if (webview) {
        webview->load(url);
    }
    return;
}